<template>
  <q-card-section class="row justify-center">
    <q-form
      class="col-12 col-lg-11 col-xl-9"
      @submit.prevent.stop="addArticle"
      @reset="formReset"
      ref="addArticle"
    >
      <div class="row q-col-gutter-md">
        <div class="col col-md-4">
          <q-select
            outlined
            dense
            v-model="Select.model"
            :options="Select.options"
            label="所属分类"
            clear-icon="mdi-close"
            clearable
            options-selected-class="text-primary"
            name="CategoryID"
          />
        </div>
        <div class="col col-md-4">
          <q-input
            outlined
            dense
            v-model="Author"
            label="发布者"
            readonly
            name="Author"
          />
        </div>
        <div class="col col-md-4">
          <q-input
            outlined
            dense
            v-model="PublicDate"
            mask="date"
            :rules="['date']"
            name="PublicDate"
          >
            <template v-slot:append>
              <q-icon
                name="mdi-calendar"
                class="cursor-pointer text-primary"
              >
                <q-popup-proxy
                  ref="qDateProxy"
                  transition-show="scale"
                  transition-hide="scale"
                >
                  <q-date v-model="PublicDate">
                    <div class="row items-center justify-end">
                      <q-btn
                        v-close-popup
                        label="关闭"
                        color="primary"
                        flat
                      />
                    </div>
                  </q-date>
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </div>
      </div>
      <div class="row">
        <div class="col col-12">
          <q-input
            outlined
            dense
            v-model="ArticleName"
            label="文章标题"
            name="ArticleName"
            :rules="[val => !!val || '请填写文章标题']"
          />
        </div>
      </div>
      <div class="row q-col-gutter-md">
        <div class="col col-12">
          <q-input
            outlined
            dense
            v-model="ArticleDescription"
            type="textarea"
            label="文章导语"
            name="ArticleDescription"
            class="q-pt-md"
          />
        </div>
      </div>
      <div class="row q-col-gutter-md">
        <div class="col col-12 q-pt-md">
          <div
            id="WEditor"
            class="q-pt-md"
          ></div>
          <q-input
            class="hidden"
            outlined
            dense
            v-model="Editor.editorData"
            type="textarea"
            label="文章内容"
            name="ArticleContent"
          />
        </div>
      </div>
      <div class="row q-col-gutter-md">
        <div class="col col-md-12">
          <q-input
            outlined
            dense
            v-model="WebLink"
            label="外链地址"
            name="WebLink"
            hint="文章会直接跳转到外链地址"
            class="q-pt-md"
          />
        </div>
      </div>
      <div class="row q-col-gutter-md">
        <div class="col col-6">
          <q-uploader
            ref="articleCover"
            flat
            bordered
            label="文章封面图"
            accept=".jpg, image/*"
            max-files="1"
            auto-upload
            class="q-mt-md full-width"
            :factory="uploadCover"
            @uploaded="uploadedInfo"
          />
          <q-input
            class="hidden"
            outlined
            dense
            v-model="ArticleCover"
            label="文章封面图地址"
            name="ArticleCover"
          />
        </div>
        <div class="col" />
        <div class="col col-md-4">
          <q-toggle
            v-model="Status"
            name="Status"
            label="文章是否审核"
            left-label
            class="q-pt-md q-ml-sm"
          />
          <div class="q-field__bottom q-field__messages col">取消审核的文章，不会删除，只是不在前台显示</div>
        </div>
      </div>
      <q-separator class="q-my-md" />
      <div class="row q-col-gutter-md">
        <q-space />
        <div class="col col-md-2">
          <q-btn
            label="重置表单"
            type="reset"
            flat
            class="full-width"
          />
        </div>
        <div class="col col-md-2">
          <q-btn
            label="返回列表"
            type="button"
            color="secondary"
            flat
            class="full-width bg-grey-4"
            @click="returnArticles"
          />
        </div>
        <div class="col col-md-2">
          <q-btn
            label="确定添加"
            type="submit"
            color="white"
            flat
            class="full-width bg-primary"
          />
        </div>
      </div>
    </q-form>
    <!-- 对话框-是否继续添加 -->
    <q-dialog v-model="dialog.addAgain">
      <q-card>
        <q-card-section class="row items-center">
          <q-avatar
            icon="mdi-alert-circle-outline"
            text-color="primary"
          />
          <span class="q-ml-sm">文章添加成功！是否继续添加？</span>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            flat
            label="返回列表"
            v-close-popup
            @click="returnArticles"
          />
          <q-btn
            flat
            label="继续添加"
            color="primary"
            v-close-popup
            @click="addAgain"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-card-section>
</template>

<script>
import WEditor from 'wangeditor'
import { mapMutations } from 'vuex'

// 定义获取二级分类的参数
const _mCode = {
  mCode: 'XW'
}

export default {
  name: 'PageAddArticle',
  components: {},
  props: {},
  data () {
    return {
      // ---------- 下拉框
      Select: {
        model: null,
        options: [],
        columnName: '',
      },
      ArticleName: '',
      Author: this.$store.state.Author,
      PublicDate: '',
      ArticleDescription: '',
      ArticleContent: '',
      ArticleCover: '',
      WebLink: '',
      Status: true,
      Editor: {
        editor: null,
        editorData: ''
      },
      // ---------- 对话框
      dialog: {
        addAgain: false,
      },
    }
  },
  methods: {
    // 获取当前日期，格式化并赋值给日期控件
    getDateNow() {
      this.PublicDate = this.$utils.initDate(Date.now(), 0, 10)
    },
    // 获取所属分类
    getCategory() {
      this.$api.MColumnOptionParams('GetMColumnList', 'get', _mCode).then (result => {
        // console.log(result)
        this.Select.options = result
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 上传封面图片
    uploadCover(files) {
      return this.$utils.uploadedIMG()
    },
    uploadedInfo(info) {
      this.ArticleCover = this.$utils.formatUploadedInfo(info)[0]
    },
    // 初始化富文本编辑器
    initEditor() {
      const wangEditor = new WEditor('#WEditor')
      // 配置 onchange 回调函数，将数据同步到 vue 中
      wangEditor.config.onchange = (newHtml) => {
        this.Editor.editorData = newHtml
      }
      wangEditor.config.height = 500
      wangEditor.config.placeholder = '文章正文'
      // 配置粘贴文本的内容处理,解决粘贴内容有换行时报错“Cannot read property ‘nodeName’ of undefined”
      wangEditor.config.pasteTextHandle = function (pasteStr) {
        // 对粘贴的文本进行处理，然后返回处理后的结果
        wangEditor.cmd.do('insertHTML', pasteStr)
      }
      // 配置 z-index
      wangEditor.config.zIndex = 500
      // 忽略粘贴内容中的图片
      wangEditor.config.pasteIgnoreImg = true
      // 取消自动 focus
      wangEditor.config.focus = false
      // 隐藏插入网络图片的功能
      wangEditor.config.showLinkImg = false
      // 配置 server 接口地址
      wangEditor.config.uploadImgServer = this.$utils.defaultImgUploadURL
      // 自定义 timeout 时间
      wangEditor.config.uploadImgTimeout = 50 * 1000
      // 配置菜单
      wangEditor.config.menus = [
        'bold',
        'underline',
        'strikeThrough',
        'link',
        'list',
        'justify',
        'quote',
        'image',
        'video',
        'table',
        'splitLine',
        'undo',
        'redo'
      ]

      // 创建编辑器
      wangEditor.create()

      this.Editor.editor = wangEditor
    },
    // 添加
    addArticle(evt) {
      if ( this.Select.model === null ) {
        this.$utils.notify('请选择文章分类', 'red-8')
      } else {
        const _addArticleResult = this.$utils.formatFormData(evt)
        // console.log(_addArticleResult)
        this.$api.ArticlesData('', 'post', _addArticleResult).then( result => {
          // console.log(result)
          if ( result === 'success') {
            this.formReset()
            this.dialog.addAgain = true
          } else if ( result === 'error' ) {
            this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
          }
        }).catch( err => {
          switch (err.response.status) {
            case 401:
              this.unauthorized()
              break
          }
          console.log(err)
        })
      }
    },
    // btn-继续添加
    addAgain() {
      this.dialog.addAgain = false
    },
    // btn-返回列表
    returnArticles() {
      this.$router.push('/Articles/Articles');
    },
    // 重置表单
    formReset() {
      this.Editor.editor.destroy()
      this.Editor.editor = null
      this.initEditor()
      this.Select.model = null
      this.ArticleName = ''
      this.getDateNow()
      this.ArticleDescription = ''
      this.ArticleContent = ''
      this.$refs.articleCover.reset()
      this.ArticleCover = ''
      this.WebLink = ''
      this.Status = true
    },
    // session过期操作
    ...mapMutations(['changeLogin']),
    unauthorized() {
      // 弹出警告框
      this.$utils.notify('身份信息过期','red-8')
      // 清除vuex中的token
      this.changeLogin({ Authorization: '' })
      // 路由跳转
      this.$router.push('/Login', onComplete => {}, onAbort => {});
    }
  },
  mounted() {
    this.initEditor()
    this.getDateNow()
    this.getCategory()
  },
  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.Editor.editor.destroy()
    this.Editor.editor = null
  }
}
</script>
<style scoped>
.q-form {
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}
</style>
